import 'package:get/get_state_manager/src/rx_flutter/rx_disposable.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class DbService extends GetxService {
  late SharedPreferences _prefs;

  Future<DbService> init() async {
    _prefs = await SharedPreferences.getInstance();
    return this;
  }

  void _setKey(String key) {
    String keysRecord = _prefs.getString("-*keys*-") ?? "-*-*-";
    if (keysRecord.contains("-*-*-${key}-*-*-")) return;
    keysRecord += "$key-*-*-";
    _prefs.setString("-*keys*-", keysRecord);
  }

  bool _delKey(String key) {
    final jsonString = _prefs.getString("funcList");
    if (jsonString == null || jsonString == "") {
      return false;
    }
    String k;
    try {
      // 解析 JSON 字符串为 List<dynamic>
      List<dynamic> list = jsonDecode(jsonString);
      list.removeWhere((element) => element['name'] == key);
      //将修改后的列表重新编码为 JSON 字符串
      k = jsonEncode(list);
    } catch (e) {
      k = jsonString;
    }
    _prefs.remove("funcList");
    _prefs.setString("funcList", k);
    return true;
    // final k = _prefs.getString("-*keys*-");
    // if (k == null) {
    //   return;
    // }
    // final t = k.split("$key-*-*-");
    // // 增加数组长度检查
    // if (t.length >= 2) {
    //   _prefs.setString("-*keys*-", t[0] + t[1]);
    // } else if (t.length == 1) {
    //   // 如果只分割出一部分，说明key可能不存在或位于末尾
    //   _prefs.setString("-*keys*-", t[0]);
    // }
  }

  List<String> getKeysByHeader(String header) {
    String keysRecord = _prefs.getString("-*keys*-") ?? "-*-*-";
    final records = keysRecord.split("-*-*-");
    List<String> r = [];
    for (var i in records) {
      if (!i.contains(header)) {
        continue;
      }
      r.add(i);
    }
    return r;
  }

  Future<bool> setValue(String key, dynamic value) async {
    _setKey(key);
    if (value.runtimeType == int) {
      _prefs.setInt(key, value);
      return true;
    }
    if (value.runtimeType == String) {
      _prefs.setString(key, value);
      return true;
    }
    if (value.runtimeType == bool) {
      _prefs.setBool(key, value);
      return true;
    }
    if (value.runtimeType == double) {
      _prefs.setDouble(key, value);
      return true;
    }
    return false;
  }

  T? getValue<T>(String key) {
    try {
      if (T == int) {
        return _prefs.getInt(key) as T;
      }
      if (T == String) {
        return _prefs.getString(key) as T;
      }
      if (T == bool) {
        return _prefs.getBool(key) as T;
      }
      if (T == double) {
        return _prefs.getDouble(key) as T;
      }
    } catch (e) {
      return null;
    }
    return null;
  }

  Future<bool> removeKey(String key) async {
    return _delKey(key);
    // return _prefs.remove(key);
  }
}
